import AMapLoader from '@amap/amap-jsapi-loader'
export function aMapLoader() {
  if (window.AMap && window.AMap.Map) {
    return Promise.resolve(window.AMap)
  }
  return new Promise((resolve) => {
    AMapLoader.load({
      key: 'a9b1e5b43ef05e7c3f3895b9815a8ec7', // 申请好的Web端开发者Key，首次调用 load 时必填
      // version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    })
      .then((AMap) => {
        return resolve(AMap)
      })
      .catch((e) => {
        console.log(e)
      })
  })
}

export function toAMapLngLat(lnglat) {
  var baidu = [lnglat.lng, lnglat.lat]
  return new Promise((resolve) => {
    aMapLoader().then(() => {
      window.AMap.convertFrom(baidu, 'baidu', (status, result) => {
        if (result.info === 'ok') {
          var lnglats = result.locations[0]
          return resolve(lnglats)
        }
      })
    })
  })
}

export function toBdMapLngLat(lnglat = {}) {
  var X_PI = (Math.PI * 3000.0) / 180.0
  var x = lnglat.lng,
    y = lnglat.lat
  var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI)
  var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI)
  var bd_lng = z * Math.cos(theta) + 0.0065
  var bd_lat = z * Math.sin(theta) + 0.006
  return {
    lat: bd_lat,
    lng: bd_lng,
  }
}
